package com.hh.demo.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hh.demo.domain.PayOrder;
import com.hh.demo.dto.PayDto;
import com.hh.demo.service.IPayOrderService;
import com.hh.demo.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 课程订单->支付订单的消费者
 * @author 黄浩
 * @create 2022-08-02 11:27
 */
@Component
@RocketMQMessageListener(
        consumerGroup = "course-order-pay-consumer",
        topic = "course-order-topic",
        selectorExpression = "course-order-tag"
)
@Slf4j
public class CourserOrder2PayOrderConsumer implements RocketMQListener<MessageExt> {
    @Resource
    private IPayOrderService payOrderService;

    /**
     * 消费消息的方法中，如果有异常，就签收失败了，此消息会滞留在mq中，等待下次的消费，直到mq自动清理垃圾
     * 如果没有异常，就签收成功了
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        AssertUtil.isNotNull(body,"消息为空！");
        String str = new String(body, StandardCharsets.UTF_8);
        PayDto payDto = JSONObject.parseObject(str, PayDto.class);
        PayOrder payOrder = payOrderService.selectOne(new EntityWrapper<PayOrder>().eq("order_no", payDto.getOrderNo()));
        if (payOrder!=null){
            //根据订单号查出来了，直接return，也就是签收此消息
            log.info("订单已存在，直接签收");
            return;
        }
        //订单不存在，说明是第一次进来消费消息，保存payOrder
        payOrder = new PayOrder();
        BeanUtils.copyProperties(payDto,payOrder);
        payOrder.setCreateTime(new Date());
        payOrder.setPayStatus(PayOrder.STATE_WAIT_PAY);
        payOrderService.insert(payOrder);
    }
}
